﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using FilStartUps.DAL;
using System.Web.Script.Services;
using System.Web.Security;
using FilStartUps.Helper;
using System.IO;
using System.Configuration;

namespace FilStartUps
{
    /// <summary>
    /// Summary description for FilStartUps_WebService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class FilStartUps_WebService : System.Web.Services.WebService
    {

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string[] GetUserEmail(string query)
        {
            using (FilStartUpsEntities db_connect = new FilStartUpsEntities())
            {
                var user = (from m in db_connect.Members
                            where m.emailaddress.StartsWith(query)
                            select m.emailaddress).Distinct();

                return user.ToArray();

            }
        }
        [WebMethod()]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public bool CheckCaptcha(string challengeValue, string responseValue)
        {
            Recaptcha.RecaptchaValidator captchaValidator = new Recaptcha.RecaptchaValidator
            {
                PrivateKey = "6Ley7skSAAAAALctlsPRhdJFwno6-DLhY6hpWYw4",
                RemoteIP = HttpContext.Current.Request.UserHostAddress,
                Challenge = challengeValue,
                Response = responseValue
            };
            Recaptcha.RecaptchaResponse recaptchaResponse = captchaValidator.Validate();

            return recaptchaResponse.IsValid;
        }
        [WebMethod()]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public bool Registration(string firstname, string lastname,
                                    string email, string confirmemail,
                                        string password, string confirmpassword,
                                            string securityquestion, string securityanswer)
        {
            using (FilStartUpsEntities db_connect = new FilStartUpsEntities())
            {
                return true;
            }
        }

        [WebMethod()]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public bool CheckEmail(string email)
        {
            using (FilStartUpsEntities db_connect = new FilStartUpsEntities())
            {
                var member = db_connect.Members.Where(m => m.emailaddress.Equals(email.Trim())).SingleOrDefault();
                if (member != null)
                {
                    return true;
                }
                else
                {
                    return false;   
                }
            }
        }

        [WebMethod()]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public bool ForgotPassword(string email, string secretquestion, string secretanswer)
        {
            using (FilStartUpsEntities db_connect = new FilStartUpsEntities())
            {
                var forgot = db_connect.Members.Where(m => m.emailaddress
                                            .Equals(email.Trim()) &&
                                            m.secretquestion.Equals(secretquestion.Trim())
                                            && m.secretanswer.Equals(secretanswer.Trim())
                                            && m.member_flag.Equals(true)).SingleOrDefault();
                if (forgot != null)
                {
                    string password = GetRandomString();
                    forgot.password = Helper.Helper.HashPassword(password);
                    forgot.confirmpassword = Helper.Helper.HashPassword(password);
                    db_connect.Entry(forgot).State = System.Data.EntityState.Modified;
                    db_connect.SaveChanges();
                    return true;
                }
                else
                {
                    return false;
                }
            }

        }

        [WebMethod()]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public bool UpdatePassword(string oldpw, string newpw, string confirmpw)
        {
            using (FilStartUpsEntities db_connect = new FilStartUpsEntities())
            {

                string password = oldpw.Trim() == "" || oldpw.Trim() == null
                     ? Helper.Helper.HashPassword("hahah") : Helper.Helper.HashPassword(oldpw.Trim());

                var member = db_connect.Members.Where(m => m.emailaddress.Equals(User.Identity.Name)
                                        && m.password.Equals(password)
                                        && m.member_flag.Equals(true)).SingleOrDefault();

                if (member != null)
                {
                    string newpassword = Helper.Helper.HashPassword(newpw.Trim());
                    member.password = newpassword;
                    member.confirmpassword = newpassword;
                    db_connect.Entry(member).State = System.Data.EntityState.Modified;
                    db_connect.SaveChanges();
                    return true;
                }
                else
                {
                    return false;
                }

            }
        }
        public static string GetRandomString()
        {
            string path = Path.GetRandomFileName();
            path = path.Replace(".", "");
            return path;
        }

        [WebMethod()]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public bool ValidateUser(string emailaddress, string password)
        {
            using (FilStartUpsEntities db_connect = new FilStartUpsEntities())
            {
                string hashpassword = password.Trim() == "" || password.Trim() == null ?
                              "wrongpassword" : Helper.Helper.HashPassword(password.Trim());
                //   && m.password.Equals(password.Trim())
                var member = db_connect.Members
                                    .Where(m => m.emailaddress.Equals(emailaddress.Trim())
                                    && m.password.Equals(hashpassword) && m.member_flag.Equals(true)
                                         ).SingleOrDefault();
                if (member != null)
                {
                    bool checksession = SessionHelper.CheckSession(member.memberidPK);
                    if (checksession == true)
                    {
                        SessionHelper.UpdateSession(member.memberidPK);
                    }
                    else
                    {
                        SessionHelper.CreateSession(member.memberidPK);
                    }

                    string role = string.Empty;

                    if (member.roleidFK == 1)
                    {
                        role = "Moderator";
                    }
                    else
                    {
                        role = "Member";
                    }
                    //Create FormsAuthenticationTicket
                    FormsAuthenticationTicket tik = new FormsAuthenticationTicket(
                        1,
                        member.emailaddress,
                        DateTime.Now,
                        DateTime.Now.AddHours(24),
                        false,
                        role,
                        FormsAuthentication.FormsCookiePath);

                    string hash = FormsAuthentication.Encrypt(tik);

                    HttpCookie cookie = new HttpCookie(
                        FormsAuthentication.FormsCookieName,
                        hash);

                    if (tik.IsPersistent) cookie.Expires = tik.Expiration;


                    Context.Response.Cookies.Add(cookie);


                    // Response.Cookies.Add(cookie);
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
    }
}
